/**
 * Copyright (c) 2006 Amgad S Youssef
 * All Rights Reserved.
 * Licensed under the Eclipse Public License - v 1.0
 * For more information see http://www.eclipse.org/legal/epl-v10.html
 */
package org.eclipsejcde.core.builder.checkers;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Enumeration;
import java.util.InvalidPropertiesFormatException;
import java.util.Properties;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.Path;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaCore;
import org.eclipsejcde.core.CheckerStatus;
import org.eclipsejcde.core.IChecker;
import org.eclipsejcde.core.ICheckerStatus;
import org.eclipsejcde.core.JCDECore;

/**
 * @author Amgad S Youssef
 *
 */
public class JCProjectPropertiesChecker implements IChecker {

	@Override
	public ICheckerStatus[] check(IResource resource) throws CoreException {
		if (!(resource instanceof IFile)) {
			return new ICheckerStatus[] {};
		}
		if (!resource.getName().endsWith(JCDECore.PROJECT_PROPERTIES_FILE_NAME)) {
			return new ICheckerStatus[] {};
		}
		try {
			IFile file = (IFile) resource;
			IProject project = file.getProject();
			if (!project.hasNature(JCDECore.NATURE_ID)) {
				return new ICheckerStatus[] {};
			}
			IJavaProject javaProject = JavaCore.create(project);
			Properties jcProjectProps = new Properties();
			jcProjectProps.loadFromXML(new FileInputStream(file.getLocation().toFile()));
			Enumeration enumeration = jcProjectProps.keys();
			while (enumeration.hasMoreElements()) {
				String javaElementName = (String) enumeration.nextElement();
				IJavaElement javaElement = javaProject.findElement(new Path(javaElementName.replace('.', '/')));
				IType type = javaProject.findType(javaElementName);
				if (javaElement == null && type == null) {
					jcProjectProps.remove(javaElementName);
				}
			}
			jcProjectProps.storeToXML(new FileOutputStream(file.getLocation().toFile()), "Java Card project properties");
			return new ICheckerStatus[] {};
		} catch (InvalidPropertiesFormatException e) {
			return new ICheckerStatus[] { new CheckerStatus(IMarker.SEVERITY_ERROR, e.getMessage()) };
		} catch (IOException e) {
			return new ICheckerStatus[] { new CheckerStatus(IMarker.SEVERITY_ERROR, e.getMessage()) };
		}
	}

}
